package com.yishuai.ollamatest1.controller;

import com.yishuai.ollamatest1.dto.ChatRequest;
import com.yishuai.ollamatest1.dto.ChatResponse;
import com.yishuai.ollamatest1.service.OllamaClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/api")
public class ChatController {
    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);
    private final OllamaClientService ollamaClientService;

    @Autowired
    public ChatController(OllamaClientService ollamaClientService) {
        this.ollamaClientService = ollamaClientService;
    }

    @PostMapping("/chat")
    public ResponseEntity<ChatResponse> chat(@RequestBody ChatRequest request) {
        try {
            logger.info("收到聊天请求: {}", request.getMessage());
            ChatResponse response = ollamaClientService.chat(request.getMessage());
            logger.info("处理完成，准备返回响应");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("处理聊天请求时出错", e);
            return ResponseEntity.ok(new ChatResponse("处理请求时出错: " + e.getMessage()));
        }
    }

    // 添加这个方法，用于处理JSON解析错误
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ChatResponse> handleException(Exception e) {
        logger.error("发生异常", e);
        return ResponseEntity.ok(new ChatResponse("系统错误: " + e.getMessage()));
    }
}